package com.kitchen.thread;

import com.kitchen.entity.Order;
import com.kitchen.entity.OrderItem;
import com.kitchen.service.OrderService;
import com.kitchen.util.FileUtil;

/**
 * 订单处理线程类 - 多线程实现
 * 模拟订单制作过程
 */
public class OrderProcessingThread extends Thread {
    private Order order;
    private OrderService orderService;
    
    public OrderProcessingThread(Order order, OrderService orderService) {
        this.order = order;
        this.orderService = orderService;
        this.setName("OrderProcessor-" + order.getOrderNumber());
    }
    
    @Override
    public void run() {
        try {
            FileUtil.writeLog("开始处理订单: " + order.getOrderNumber());
            
            // 模拟制作过程
            for (OrderItem item : order.getItems()) {
                FileUtil.writeLog("正在制作: " + item.getDishName() + " x" + item.getQuantity());
                
                // 模拟制作时间（实际应该从菜品信息获取）
                Thread.sleep(1000); // 1秒模拟
                
                item.setStatus("已完成");
                FileUtil.writeLog("完成制作: " + item.getDishName());
            }
            
            // 完成订单
            orderService.completeOrder(order.getOrderId());
            FileUtil.writeLog("订单处理完成: " + order.getOrderNumber());
            
        } catch (InterruptedException e) {
            FileUtil.writeLog("订单处理被中断: " + order.getOrderNumber());
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            FileUtil.writeLog("订单处理出错: " + order.getOrderNumber() + ", 错误: " + e.getMessage());
        }
    }
}

